package com.htfyun.fragment.library.child;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.htfyun.fragment.library.TreeFragment;
import com.htfyun.fragment.library.adapter.LibraryRecyclerViewAdapter;
import com.htfyun.fragment.library.adapter.TreeRecyclerViewAdapter;
import com.htfyun.fragment.listener.OnRecyclerViewItemClickListener;
import com.htfyun.view.CustomGridLayoutManager;

import org.geometerplus.android.fbreader.FBReader;
import org.geometerplus.android.fbreader.libraryService.BookCollectionShadow;
import org.geometerplus.fbreader.Paths;
import org.geometerplus.fbreader.book.Book;
import org.geometerplus.fbreader.book.BookEvent;
import org.geometerplus.fbreader.book.IBookCollection;
import org.geometerplus.fbreader.formats.PluginCollection;
import org.geometerplus.fbreader.library.ExternalViewTree;
import org.geometerplus.fbreader.library.LibraryTree;
import org.geometerplus.fbreader.tree.FBTree;
import org.geometerplus.zlibrary.ui.android.R;

import me.yokeyword.fragmentation.anim.DefaultNoAnimator;
import me.yokeyword.fragmentation.anim.FragmentAnimator;

/**
 * Created by sst on 2017/11/1.
 */

public abstract class LibraryBaseFragment extends TreeFragment<LibraryTree> implements IBookCollection.Listener<Book> {

    private RecyclerView mRecy;
    private LibraryRecyclerViewAdapter mAdapter;

    private volatile LibraryTree myRootTree;

    private TextView txtLibraryItemTotal;
    private TextView txtLibraryItemPage;

    private final BookCollectionShadow myCollection = new BookCollectionShadow();

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.htfyun_fragment_list_menu, container, false);
        initView(view);
        return view;
    }

    @Override
    public FragmentAnimator onCreateFragmentAnimator() {
        return new DefaultNoAnimator();
    }

    private void initView(View view) {
        mRecy = (RecyclerView) view.findViewById(R.id.recy);

//        CustomLinearLayoutManager layoutManager = new CustomLinearLayoutManager(_mActivity);
//        layoutManager.setScrollEnabled(false);

        CustomGridLayoutManager layoutManager = new CustomGridLayoutManager(_mActivity, 5,
                LinearLayoutManager.HORIZONTAL, false);
        
        mRecy.setLayoutManager(layoutManager);
        mAdapter = new LibraryRecyclerViewAdapter(this);
        mRecy.setAdapter(mAdapter);

       mAdapter.setOnRecyclerViewItemClickListener(new OnRecyclerViewItemClickListener() {
           @Override
           public void onItemClick(int position, View view, RecyclerView.ViewHolder vh) {
               final LibraryTree tree = (LibraryTree)getTreeAdapter().getItem(position);
               if (tree instanceof ExternalViewTree) {
               } else {
                   final Book book = tree.getBook();
                   if (book != null) {

                       FBReader.openBookActivity(getContext(), book, null);

                   } else {
                       openTree(tree);
                   }
               }
           }
       });
        
       txtLibraryItemTotal = (TextView) view.findViewById(R.id.txtLibraryItemTotal); 
       txtLibraryItemPage = (TextView) view.findViewById(R.id.txtLibraryItemPage);
       txtLibraryItemPage.setText("    ");
        
       view.findViewById(R.id.imgPrevious).setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View v) {
               RecyclerView.LayoutManager layoutManager = mRecy.getLayoutManager();

               //判断是当前layoutManager是否为LinearLayoutManager
               // 只有LinearLayoutManager才有查找第一个和最后一个可见view位置的方法
               if (layoutManager instanceof LinearLayoutManager) {
                   LinearLayoutManager linearManager = (LinearLayoutManager) layoutManager;
                   //获取最后一个可见view的位置
                   int lastItemPosition = linearManager.findLastCompletelyVisibleItemPosition();
                   //获取第一个可见view的位置
                   int firstItemPosition = linearManager.findFirstCompletelyVisibleItemPosition();

                   if (firstItemPosition == 0) {
                       setTextLibraryItemPageByPosition(firstItemPosition);
                       return;
                   }
                 
                   final int showItemCount = lastItemPosition - firstItemPosition;
                   int newPosition = firstItemPosition - showItemCount;// + 1;

                   if (newPosition < 0) {
                       newPosition = 0;
                   }

                   setTextLibraryItemPageByPosition(newPosition);

                   linearManager.scrollToPosition(newPosition);
               }
               
           }
       });

        view.findViewById(R.id.imgNext).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                RecyclerView.LayoutManager layoutManager = mRecy.getLayoutManager();

                //判断是当前layoutManager是否为LinearLayoutManager
                // 只有LinearLayoutManager才有查找第一个和最后一个可见view位置的方法
                if (layoutManager instanceof GridLayoutManager) {
                    GridLayoutManager manager = (GridLayoutManager) layoutManager;
                    //获取最后一个可见view的位置
                    int lastItemPosition = manager.findLastCompletelyVisibleItemPosition();
                    //获取第一个可见view的位置
                    int firstItemPosition = manager.findFirstCompletelyVisibleItemPosition();

                    if (lastItemPosition == mAdapter.getItemCount() - 1) {
                        setTextLibraryItemPageByPosition(lastItemPosition);
                        
                        return;
                    }

                    final int showItemCount = lastItemPosition - firstItemPosition;
                    int newPosition = lastItemPosition + showItemCount;// - 1;

                    if (newPosition > mAdapter.getItemCount() - 1) {
                        
                        newPosition = mAdapter.getItemCount() - 1;
                    }

                    setTextLibraryItemPageByPosition(newPosition);
                  
                    manager.scrollToPosition(newPosition);
                }
                
                
            }
        });

        deleteRootTree();

        myCollection.bindToService(getContext(), new Runnable() {
            public void run() {

                myRootTree = initRootTree(myCollection, PluginCollection.Instance(Paths.systemInfo(getContext())));
                myCollection.addListener(LibraryBaseFragment.this);
                openTree(myRootTree, false);
                
            }
        });

    }

    private synchronized void deleteRootTree() {
        if (getRootTree() != null) {
            myCollection.removeListener(this);
            myCollection.unbind();
            myRootTree = null;
        }
    }

    @Override
    public void onDestroy() {
        deleteRootTree();
        super.onDestroy();
    }


    @Override
    protected LibraryTree getTreeByKey(FBTree.Key key) {
        if (getRootTree() == null) {
            return null;
        }
        return key != null ? getRootTree().getLibraryTree(key) : getRootTree();
    }

    @Override
    public TreeRecyclerViewAdapter getTreeAdapter() {
        return mAdapter;
    }

    @Override
    public void treeInitOver(LibraryTree currentTree) {

        int totalCount = currentTree.subtrees().size();
        txtLibraryItemTotal.setText(getString(R.string.library_item_total, totalCount ));
        
        RecyclerView.LayoutManager layoutManager = mRecy.getLayoutManager();
//        判断是当前layoutManager是否为LinearLayoutManager
//        只有LinearLayoutManager才有查找第一个和最后一个可见view位置的方法
        if (layoutManager instanceof GridLayoutManager) {
            GridLayoutManager manager = (GridLayoutManager) layoutManager;

            //获取最后一个可见view的位置
            int lastItemPosition = manager.findLastCompletelyVisibleItemPosition();
            //获取第一个可见view的位置
            int firstItemPosition = manager.findFirstCompletelyVisibleItemPosition();

            setTextLibraryItemPageByPosition(firstItemPosition );

        }

    }

    private int getTotalPages() {
        RecyclerView.LayoutManager layoutManager = mRecy.getLayoutManager();
//        判断是当前layoutManager是否为LinearLayoutManager
//        只有LinearLayoutManager才有查找第一个和最后一个可见view位置的方法
        if (layoutManager instanceof GridLayoutManager) {
            GridLayoutManager manager = (GridLayoutManager) layoutManager;

            int span = manager.getSpanCount();

            int pages = mAdapter.getItemCount() / span;
            if (mAdapter.getItemCount() % span != 0) {
                pages += 1;
            }

            return pages;

        }

        return 1;
    }

    private int getSpanCount() {
        RecyclerView.LayoutManager layoutManager = mRecy.getLayoutManager();
//        判断是当前layoutManager是否为LinearLayoutManager
//        只有LinearLayoutManager才有查找第一个和最后一个可见view位置的方法
        if (layoutManager instanceof GridLayoutManager) {
            GridLayoutManager manager = (GridLayoutManager) layoutManager;

            return manager.getSpanCount();

        }

        return 1;
    }

    private void setTextLibraryItemPageByPosition(int position) {

        final int page = position / getSpanCount() + 1;
        txtLibraryItemPage.setText(page + "/" + getTotalPages());

    }

    protected  LibraryTree getRootTree() {
        return myRootTree;
    }

    protected abstract LibraryTree initRootTree(IBookCollection collection, PluginCollection pluginCollection);


    /////////////////////
    // IBookCollection.Listener<Book>
    /////////////////////
    @Override
    public void onBookEvent(BookEvent event, Book book) {
        if (getCurrentTree().onBookEvent(event, book)) {
            getTreeAdapter().replaceAll(getCurrentTree().subtrees());
        }
    }

    @Override
    public void onBuildEvent(IBookCollection.Status status) {

    }

}
